package com.hzncc.flowable_diboot.interfacelog.aspect;

import com.diboot.core.util.ContextHolder;
import com.diboot.core.util.JSON;
import com.hzncc.flowable_diboot.interfacelog.annotation.InterfaceLog;
import com.hzncc.flowable_diboot.interfacelog.service.InterfaceLogService;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
@Log4j2
public class InterfaceAspect {

    @Pointcut("@annotation(com.hzncc.flowable_diboot.interfacelog.annotation.InterfaceLog)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) {
        Object[] args = pjp.getArgs();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        InterfaceLog annotation = method.getAnnotation(InterfaceLog.class);
        String code = annotation.code();
        String name = annotation.name();
        String direction = annotation.direction();
        long start = System.currentTimeMillis();
        Object proceed = null;
        String exp = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable e) {
            exp = e.getMessage();
            throw new RuntimeException(e);
        } finally {
            InterfaceLogService service = ContextHolder.getBean(InterfaceLogService.class);
            com.hzncc.flowable_diboot.interfacelog.entity.InterfaceLog interfaceLog = new com.hzncc.flowable_diboot.interfacelog.entity.InterfaceLog();
            interfaceLog.setCode(code).setName(name).setDirection(direction)
                    .setRequest(Arrays.toString(args)).setRespons(JSON.stringify(proceed))
                    .setTimeout(String.valueOf(System.currentTimeMillis() - start))
                    .setException(exp);
            try {
                service.createEntity(interfaceLog);
            } catch (Exception e) {
                log.error("接口日志记录失败", e);
            }
        }
        return proceed;
    }
}
